<template>
  <div>
    <el-dialog
      :close-on-click-modal="false"
      v-model="visibleDialog"
      :title="props.title"
      :destroy-on-close="true"
      :width="!props.isReadonly ? '1100px' : '1100px'"
      :align-center="true"
      draggable
      @close="closeDialog"
      style="min-width: 1100px"
      class="maxhDialog"
    >
      <el-form
        ref="formRef"
        :model="formData"
        :rules="rules"
        label-width="120"
        v-show="!props.isReadonly"
        style="width: 99%"
      >
        <el-row>
          <el-col :span="24">
            <el-form-item label="产品" prop="productIds" style="width: 100%">
              <el-transfer
                :data="productList"
                style="
                  text-align: center;
                  display: inline-block;
                  width: 100%;
                  min-width: 100%;
                "
                :filterable="true"
                :props="{
                  key: 'id',
                  label: 'materialName',
                }"
                :titles="['可用产品', '已选产品']"
                v-model="formData.productIds"
              />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="点检名称" prop="sopTypeId">
              <el-select
                v-model="formData.sopTypeId"
                placeholder="请选择点检名称"
                clearable
                style="width: 100%"
              >
                <el-option
                  v-for="item in typeList"
                  :key="item.id"
                  :label="item.sopTypeName"
                  :value="item.id"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="模具类型" prop="equipTypeId">
              <el-tree-select
                v-model="formData.equipTypeId"
                node-key="id"
                :check-strictly="true"
                :props="{
                  children: 'nodes',
                  label: 'assetTypeName',
                }"
                placeholder="请选择模具类型"
                :data="deviceList"
                filterable
                clearable
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="是否启用" prop="enabled">
              <el-radio-group v-model="formData.enabled">
                <el-radio :label="1">启用</el-radio>
                <el-radio :label="0">停用</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>

        <el-tabs type="border-card">
          <el-tab-pane label="作业指导书">
            <CommonUploadFile
              :isRead="props.isReadonly"
              :files="formData.images"
              @update-files="updateFormFiles"
            />
          </el-tab-pane>
        </el-tabs>
      </el-form>

      <el-descriptions
        v-show="props.isReadonly"
        title=""
        :column="2"
        size="large"
        border
        style="width: 99%; max-height: 70vh; overflow-y: auto"
      >
        <el-descriptions-item>
          <template #label>
            <div class="cell-item" v-if="props.assetKind == 3">产品</div>
          </template>
          {{
            formData.products.length > 0
              ? formData.products.map((item) => item.materialName).join(",")
              : ""
          }}
        </el-descriptions-item>
        <el-descriptions-item>
          <template #label>
            <div class="cell-item">点检名称</div>
          </template>
          {{ formData.sopTypeName || "" }}
        </el-descriptions-item>
        <el-descriptions-item>
          <template #label>
            <div class="cell-item">模具类型</div>
          </template>
          {{ formData.assetTypeName || "" }}
        </el-descriptions-item>

        <el-descriptions-item>
          <template #label>
            <div class="cell-item">是否启用</div>
          </template>
          <el-tag v-show="formData.enabled === 1" type="">启用</el-tag>
          <el-tag v-show="formData.enabled !== 1" type="info">停用</el-tag>
        </el-descriptions-item>
        <el-descriptions-item :span="3">
          <template #label>
            <div class="cell-item">作业指导书</div>
          </template>
          <div v-if="formData.images && formData.images.length">
            <CommonUploadFile
              :showText="false"
              :isRead="props.isReadonly"
              :files="formData.images"
              @update-files="updateFormFiles"
            />
          </div>
          <div v-else>无</div>
        </el-descriptions-item>
      </el-descriptions>

      <template #footer>
        <div class="dialog-footer">
          <el-button
            v-if="!props.isReadonly"
            type="primary"
            :loading="loading"
            @click="handleSubmit"
            >确 定</el-button
          >
          <el-button @click="closeDialog">取 消</el-button>
        </div>
      </template>
    </el-dialog>
    <SelectMaterialDialog
      v-model:visible="materialSelect.visible"
      :data="materialSelect.data"
      :isMultiple="false"
      :materialType="9"
      @echo-info="getMaterialSelect"
    />
    <!-- <SelectMaterialDialog
      v-model:visible="materialSelect.visible"
      :data="materialSelect.data"
      :isMultiple="false"
      @echo-info="getMaterialSelect"
    /> -->
  </div>
</template>

<script setup lang="ts">
import request from "@/utils/request";
import { useDictStoreHook } from "@/store/modules/dictionary"; // 引入
import {
  getStandardTypesApi,
  getStandardDevicesApi,
  getMakerListApi,
  getBrandModelListApi,
} from "@/utils/commonData";
import { validateNumberCanNot } from "@/utils/commonHooks";

const dictionaryStore = useDictStoreHook();

defineOptions({
  name: "CommonWorkStandardEdit",
  inheritAttrs: false,
});

const emit = defineEmits(["reset-table", "change-visible"]);

const props = defineProps({
  visible: {
    type: Boolean,
    default: () => {
      return false;
    },
  },
  title: {
    type: String,
    default: () => {
      return "";
    },
  },
  data: {
    type: Object,
    default: () => {
      return {};
    },
  },
  isReadonly: {
    type: Boolean,
    default: () => {
      return false;
    },
  },
  assetKind: {
    type: Number,
    default: null,
  },
  sopTypeCode: {
    type: String,
    default: "",
  },
  taskKind: {
    type: String,
    default: null,
  },
});

const visibleDialog = ref(false);
const formRef = ref(ElForm);
watch(
  () => props.visible,
  (newVal: boolean) => {
    visibleDialog.value = newVal;
    setTimeout(() => {
      formRef.value && formRef.value.clearValidate();
    }, 50);
  }
);

const rules = reactive(<any>{
  remarks: [
    { message: "请输入备注", trigger: "blur" },
    { max: 255, message: "不能超过255个字符", trigger: "blur" },
  ],
  enabled: [{ required: true, message: "请选择是否启用", trigger: "change" }],
  standardCode: [
    { required: true, message: "请输入作业编号", trigger: "blur" },
    { max: 32, message: "不能超过32个字符", trigger: "blur" },
  ],
  standardName: [
    { required: true, message: "请输入作业名称", trigger: "blur" },
    { min: 1, max: 50, message: "不能超过50个字符", trigger: "blur" },
  ],
  sopTypeId: [{ required: true, message: "请选择作业类型", trigger: "change" }],
  equipTypeId: [
    // { required: true, message: "请选择模具类型", trigger: "change" },
  ],
  standardCycle: [
    {
      required: false,
      message: "请输入周期",
      trigger: "blur",
    },
    {
      validator: validateNumberCanNot,
      trigger: "blur",
    },
  ],
  standardPersonnel: [
    { required: true, message: "请选择作业人员类型", trigger: "change" },
  ],
  standardCompilePersonnel: [
    { min: 1, max: 32, message: "不能超过32个字符", trigger: "blur" },
  ],
  standardExaminePersonnel: [
    { min: 1, max: 32, message: "不能超过32个字符", trigger: "blur" },
  ],
  standardRatifyPersonnel: [
    { min: 1, max: 32, message: "不能超过32个字符", trigger: "blur" },
  ],
});

let formData = reactive({
  id: "",
  version: "",
  remarks: "",
  standardCode: "",
  standardName: "",
  sopTypeId: "",
  standardCategory: "",
  assetKind: props.assetKind,
  sopTypeCode: props.sopTypeCode,
  equipTypeId: "",
  standardCycle: "",
  standardCycleType: "1",
  standardPersonnel: "",
  standardCompileTime: "",
  standardCompilePersonnel: "",
  standardExamineTime: "",
  standardExaminePersonnel: "",
  standardRatifyTime: "",
  standardRatifyPersonnel: "",
  createTime: "",
  createdUserId: "",
  createdUserName: "",
  lastUpdateTime: "",
  lastUpdatedUserId: "",
  lastUpdatedUserName: "",
  enabled: 1,
  deleted: "",
  images: [],
  products: [],
  productIds: [],
  sopTypeName: "",
  assetTypeName: "",
  brandId: "",
  brandName: "",
  makerId: "",
  makerName: "",
  makerCode: "",
  modelNo: "",
  assetModelId: "",
});

watch(
  () => props.data,
  (newVal: any) => {
    formData.id = "";

    if (newVal?.id) {
      const {
        id,
        version,
        remarks,
        standardCode,
        standardName,
        sopTypeId,
        standardCategory,
        assetKind,
        sopTypeCode,
        equipTypeId,
        brandId,
        brandName,
        makerId,
        makerName,
        makerCode,
        modelNo,
        assetModelId,
        standardCycle,
        standardCycleType,
        standardPersonnel,
        standardCompileTime,
        standardCompilePersonnel,
        standardExamineTime,
        standardExaminePersonnel,
        standardRatifyTime,
        standardRatifyPersonnel,
        createTime,
        createdUserId,
        createdUserName,
        lastUpdateTime,
        lastUpdatedUserId,
        lastUpdatedUserName,
        enabled,
        deleted,
        images,
        products,
        sopTypeName,
        assetTypeName,
      } = newVal;
      Object.assign(formData, {
        id,
        version,
        remarks,
        standardCode,
        standardName,
        sopTypeId,
        standardCategory,
        assetKind,
        sopTypeCode,
        equipTypeId,
        brandId,
        brandName,
        makerId,
        makerName,
        makerCode,
        modelNo,
        assetModelId,
        standardCycle,
        standardCycleType,
        standardPersonnel,
        standardCompileTime,
        standardCompilePersonnel,
        standardExamineTime,
        standardExaminePersonnel,
        standardRatifyTime,
        standardRatifyPersonnel,
        createTime,
        createdUserId,
        createdUserName,
        lastUpdateTime,
        lastUpdatedUserId,
        lastUpdatedUserName,
        enabled,
        deleted,
        images: images ?? [],
        products,
        sopTypeName,
        assetTypeName,
      });
      formData.productIds = products?.map((item: any) => item.materialId);
      handleMakerChange(makerId, "");
    } else {
      formData.images = [];
      formData.productIds = [];
      formData.enabled = 1;
      formData.assetKind = props.assetKind;
    }
  }
);

/** 关闭表单弹窗 */
function closeDialog() {
  visibleDialog.value = false;
  emit("change-visible", false);
  resetForm();
}

/** 重置表单 */
function resetForm() {
  if (formRef.value) {
    formRef.value.resetFields();
    formRef.value.clearValidate();
  }
  formData.id = "";
  formData.version = "";
  formData.remarks = "";
  formData.standardCode = "";
  formData.standardName = "";
  if (!props.sopTypeCode) formData.sopTypeId = "";
  formData.standardCategory = "";
  formData.assetKind = props.assetKind;
  formData.equipTypeId = "";
  formData.brandId = "";
  formData.brandName = "";
  formData.makerId = "";
  formData.makerName = "";
  formData.makerCode = "";
  formData.modelNo = "";
  formData.assetModelId = "";
  formData.standardCycle = "";
  formData.standardCycleType = "1";
  formData.standardPersonnel = "";
  formData.standardCompileTime = "";
  formData.standardCompilePersonnel = "";
  formData.standardExamineTime = "";
  formData.standardExaminePersonnel = "";
  formData.standardRatifyTime = "";
  formData.standardRatifyPersonnel = "";
  formData.createTime = "";
  formData.createdUserId = "";
  formData.createdUserName = "";
  formData.lastUpdateTime = "";
  formData.lastUpdatedUserId = "";
  formData.lastUpdatedUserName = "";
  formData.enabled = 1;
  formData.deleted = "";
  formData.sopTypeName = "";
  formData.assetTypeName = "";
}

const loading = ref(false);

/** 标准作业规程保存提交 */
function handleSubmit() {
  formRef.value.validate(async (valid: any) => {
    if (valid) {
      loading.value = true;
      const text = formData.id ? "编辑" : "新增";
      if (formData.productIds.length === 0) {
        loading.value = false;
        return ElMessage.error("请选择产品");
      }
      formData.products = formData.productIds.map((item) => {
        const find = productList.value.find((t) => t.id === item);
        if (find)
          return {
            materialCode: find.materialCode,
            materialName: find.materialName,
            materialId: find.id,
          };
      });
      await request({
        url: "/eam/eamsopstandard/save",
        method: "post",
        data: formData,
      }).finally(() => {
        loading.value = false;
      });
      ElMessage.success(text + `成功`);
      closeDialog();
      emit("reset-table", formData.id);
    }
  });
}

// 组件销毁时调用
onBeforeUnmount(() => {
  visibleDialog.value = false;
  emit("change-visible", false);
});

// 获取作业类型列表
const typeList = ref(<any>[]);
async function getTypeList(value: string) {
  const params = {
    taskKind: props.taskKind,
    assetKind: props.assetKind,
  };
  typeList.value = (await getStandardTypesApi(params)) ?? [];
}

// 获取作业类型列表
const deviceList = ref(<any>[]);
async function getDeviceList() {
  const params = {
    assetKind: props.assetKind,
  };
  deviceList.value = (await getStandardDevicesApi(params)) ?? [];
}
getDeviceList();

// 图片处理
function updateFormFiles(val: []) {
  formData.images = val;
}

// 点击制造商 返回品牌和型号
const brandModelList = ref(<any>[]);
const handleMakerChange = async (e, row) => {
  if (row) {
    formData.brandId = "";
    formData.brandName = "";
    formData.modelNo = "";
    formData.assetModelId = "";
  }

  if (e) {
    brandModelList.value = [];
    const params = { makerId: e, assetKind: props.assetKind };
    brandModelList.value = (await getBrandModelListApi(params)) ?? [];
  } else {
    formData.makerId = "";
    formData.makerName = "";
    formData.makerCode = "";
    brandModelList.value = [];
  }
};

// 点击品牌 赋值
const handelBrandModelNo = (e) => {
  if (e) {
    brandModelList.value.forEach((item: any) => {
      if (item.id == e) {
        formData.assetModelId = item.id;
        formData.brandId = item.brandId;
        formData.brandName = item.brandName;
        formData.modelNo = item.modelNo;
      }
    });
  } else {
    formData.brandId = "";
    formData.brandName = "";
    formData.modelNo = "";
    formData.assetModelId = "";
  }
};

// 获取制造商列表
const makerList: any = ref([]);
const getMakerList = async () => {
  const params = {
    assetKind: props.assetKind,
  };
  makerList.value = (await getMakerListApi(params)) ?? [];
};
const sopType = ref();
onMounted(async () => {
  getMakerList();
  getProductList();
  await getTypeList("");
  if (props.sopTypeCode) {
    sopType.value =
      typeList.value.find(
        (item: any) => item.sopTypeCode === props.sopTypeCode
      ) || "";
    formData.sopTypeId = sopType.value?.id;
  }
});

// 定义 物料选择器弹窗参数
const materialSelect = reactive<DialogOption>({
  visible: false,
  data: [],
});

const materialOptions: any = ref([]); // 选择器 list

// 打开 物料选择器弹窗
function openMaterialDialog() {
  if (formData.standardCode) {
    materialOptions.value = [
      {
        materialCode: formData.standardCode,
      },
    ];
  }
  materialSelect.visible = true;
  materialSelect.data = materialOptions.value;
}

// 接收 物料选择器回调参数
function getMaterialSelect(options: any) {
  formData.standardCode = options[0]?.materialCode || "";
}
// 获取产品信息下拉树
const productList: any = ref([]);
const getProductList = async () => {
  const { data } = await request({
    url: "/mdm/mdmmaterial/getList",
    method: "POST",
    data: { materialType: "3" },
  });
  productList.value = data;
};
</script>

<style scoped lang="scss">
:deep(.maxhDialog .el-dialog__body) {
  max-height: 70vh;
  overflow-y: auto;
}
.el-form-item {
  margin-bottom: 15px;
}
:deep(.el-descriptions__label.el-descriptions__cell.is-bordered-label) {
  width: 120px;
}
:deep(.el-descriptions__content.el-descriptions__cell.is-bordered-content) {
  min-width: 180px;
}
:deep(.moldEnterInspect) {
  .el-input__inner {
    background-color: #fff !important;
  }
  .el-input__wrapper {
    background-color: #fff !important;
  }
  .el-input-group__append {
    cursor: pointer;
    padding: 0;
    > div {
      padding: 0 20px;
    }
  }
}
:deep(.el-transfer-panel) {
  width: 40%;
}
</style>
